<script>
import FormPanel1 from '../../components/FormPanel/FormPanel';
import yyImage from '../../components/yyImage/main.vue';
import _ from 'lodash';
import axios from 'axios';
import { getConfigHeaders } from '@/api/fetch';
export default {
  name: 'FormPanel',
  extends: FormPanel1,
  methods: {
    createSelectHandle(option, multiple = false) {
      const { form } = this;
      const { label, fieldName, labelWidth, labelOptions, descOptions, filterable, request = {}, style = {}, placeholder = '请选择...', disabled, clearable = !0, change = () => { } } = option;
      const { fetchApi, params = {} } = request;
      let { itemList } = option;
      if (!option.itemList && fetchApi) {
        itemList = this[`${fieldName}ItemList`] || [];
        if (!_.isEqual(this[`${fieldName}PrevParams`], params)) {
          this[`${fieldName}PrevParams`] = params;
          this.querySelectOptions(request, fieldName);
        }
      }
      return (
        <el-form-item key={fieldName} label={label} labelWidth={labelWidth} prop={fieldName}>
          {labelOptions && <span slot="label">{this.createFormItemLabel(labelOptions)}</span>}
          <el-select
            multiple={multiple}
            collapseTags={!disabled}
            filterable={filterable}
            v-model={form[fieldName]}
            placeholder={placeholder}
            disabled={disabled}
            style={{ ...style }}
            clearable={clearable}
            onChange={change}
            filterMethod={queryString => {
              if (!filterable) return;
              this.filterMethodHandle(fieldName, queryString);
            }}
            on-visible-change={val => {
              if (filterable && !val) {
                setTimeout(() => this.filterMethodHandle(fieldName, ''), 300);
              }
            }}
          >
            {itemList.map(x => (
              <el-option key={x.value} label={x.text} value={x.value} disabled={x.disabled} />
            ))}
          </el-select>
          {this.createFormItemDesc(descOptions)}
        </el-form-item>
      );
    },
    TEXT_AREA(option) {
      const { form } = this;
      const { label, fieldName, labelWidth, labelOptions, style = {}, placeholder = '请输入...', disabled, rows = 2, maxlength = 200 } = option;
      return (
        <el-form-item key={fieldName} label={label} labelWidth={labelWidth} prop={fieldName}>
          {labelOptions && <span slot="label">{this.createFormItemLabel(labelOptions)}</span>}
          <el-input
            type="textarea"
            v-model={form[fieldName]}
            placeholder={!disabled ? placeholder : ''}
            disabled={disabled}
            style={{ ...style }}
            clearable
            autosize={{ minRows: rows }}
            maxlength={maxlength}
            onInput={val => {
              //  val=String(val).replace(/^\s+|\s+$/g, '') //去除前后空格
              form[fieldName] = val;
            }}
            showWordLimit
          />
        </el-form-item>
      );
    },
    DATE(option) {
      const { form } = this;
      const isIe = window.showModalDialog ? true : false;
      const conf = {
        date: {
          placeholder: '选择日期',
          valueFormat: 'yyyy-MM-dd HH:mm:ss'
        },
        datetime: {
          placeholder: '选择时间',
          valueFormat: 'yyyy-MM-dd HH:mm:ss'
        },
        exactdatetime: {
          placeholder: '选择时间',
          valueFormat: 'yyyy-MM-dd HH'
        },
        exactdate: {
          placeholder: '选择日期',
          valueFormat: 'yyyy-MM-dd'
        },
        month: {
          placeholder: '选择月份',
          valueFormat: 'yyyy-MM'
        },
        year: {
          placeholder: '选择年份',
          valueFormat: 'yyyy'
        }
      };
      const { label, fieldName, labelWidth, labelOptions, valueFormat, dateType = 'date', minDateTime, maxDateTime, format, style = {}, disabled, change = () => { }, popperClassName = '' } = option;
      if (isIe) {
        return (
          <el-form-item key={fieldName} label={label} labelWidth={labelWidth} prop={fieldName}>
            {labelOptions && <span slot="label">{this.createFormItemLabel(labelOptions)}</span>}
            <el-date-picker
              type={dateType.replace('exact', '')}
              value={this.formatDate(form[fieldName], format || conf[dateType].valueFormat)}
              onInput={val => {
                val = val === null ? undefined : val;
                form[fieldName] = val;
              }}
              value-format={format || conf[dateType].valueFormat}
              format={format || valueFormat || conf[dateType].valueFormat} //cms注意
              // placeholder={conf[dateType].placeholder}
              disabled={disabled}
              popper-class={popperClassName}
              style={{ ...style }}
              picker-options={{
                disabledDate: time => {
                  return this.setDisabledDate(time, [minDateTime, maxDateTime]);
                }
              }}
              onChange={() => change(form[fieldName])}
            />
          </el-form-item>
        );
      } else {
        return (
          <el-form-item key={fieldName} label={label} labelWidth={labelWidth} prop={fieldName}>
            {labelOptions && <span slot="label">{this.createFormItemLabel(labelOptions)}</span>}
            <el-date-picker
              type={dateType.replace('exact', '')}
              value={this.formatDate(form[fieldName], format || conf[dateType].valueFormat)}
              onInput={val => {
                val = val === null ? undefined : val;
                form[fieldName] = val;
              }}
              value-format={format || conf[dateType].valueFormat}
              format={format || valueFormat || conf[dateType].valueFormat} //cms注意
              placeholder={conf[dateType].placeholder}
              disabled={disabled}
              popper-class={popperClassName}
              style={{ ...style }}
              picker-options={{
                disabledDate: time => {
                  return this.setDisabledDate(time, [minDateTime, maxDateTime]);
                }
              }}
              onChange={() => change(form[fieldName])}
            />
          </el-form-item>
        );
      }
    },
    DATES(option) {
      const { form } = this;
      const { label, fieldName, labelWidth, labelOptions, placeholder, dateType = 'dates', style = {}, disabled, change = () => { } } = option;
      return (
        <el-form-item key={fieldName} label={label} labelWidth={labelWidth} prop={fieldName}>
          {labelOptions && <span slot="label">{this.createFormItemLabel(labelOptions)}</span>}
          <el-date-picker type={dateType} v-model={form[fieldName]} placeholder={placeholder} value-format="yyyy-MM-dd" disabled={disabled} style={{ ...style }} onChange={change} />
        </el-form-item>
      );
    },
    // UPLOAD_FILE(option) {
    //   const { form } = this;
    //   const { label, fieldName, tip = false, fail = false, labelWidth, labelOptions, upload = {}, style = {}, disabled, change = () => {} } = option;
    //   let { actionUrl, limit = 1, min = 0, max = 5120, fileTypes } = upload;
    //   const uploadProps = {
    //     props: {
    //       action: actionUrl,
    //       fileList: form[fieldName],
    //       headers: getConfigHeaders(),
    //       limit,
    //       multiple: false,
    //       withCredentials: true,
    //       disabled,
    //       onPreview: this.previewFileHandle,
    //       onExceed: (file, fileList) => {
    //         this.$notify({ title: `只能上传${limit}个文件`, type: 'warning' });
    //       },
    //       beforeUpload: file => this.beforeUploadHandle(file, fileTypes, form[fieldName], upload),
    //       beforeRemove: (file, fileList) => this.beforeRemove(fieldName, file, fileList),
    //       onRemove: (file, fileList) => this.handleRemove(fieldName, file, fileList),
    //       onSuccess: (res, file, fileList) => {
    //         change(res);
    //         this.successHandle(fieldName, res, file, fileList);
    //       }
    //     }
    //   };
    //   let imgArray = [];
    //   let fileArray = [];
    //   if (this.formType === 'show' || disabled) {
    //     let copyForm = Object.assign([], form[fieldName]);
    //     copyForm.map(i => {
    //       let typeName = i.name.split('.');
    //       let type = typeName[typeName.length - 1];
    //       if (type === 'JPEG' || type === 'jpeg' || type === 'png' || type === 'PNG' || type === 'jpg' || type === 'JPG' || type === 'gif' || type === 'GIF') {
    //         imgArray.push(i);
    //       } else {
    //         fileArray.push(i);
    //       }
    //     });
    //   }
    //   //修改 start
    //   return (
    //     <el-form-item key={fieldName} label={label} ref={fieldName} labelWidth={labelWidth} prop={fieldName}>
    //       {labelOptions && <span slot="label">{this.createFormItemLabel(labelOptions)}</span>}
    //       {this.formType === 'show' || disabled ? (
    //         <div>
    //           {form[fieldName].length > 0 ? (
    //             <div>
    //               {imgArray.map(x => {
    //                 return (
    //                   <span style="position: relative;display:inline-block; border:#ddd solid 1px; margin-right:10px;">
    //                     <yyImage class="imgDIy" style="width: 100px;overflow: hidden; height:100px; display:block;" src={x.url} preview-src-list={[x.url]}></yyImage>
    //                     <div class="imgName">{x.name}</div>
    //                     {x.url && x.url !== '' && !fail ? <a class="el-icon-download fileName" target="_blank" download={x.name} href={x.url}></a> : null}
    //                   </span>
    //                 );
    //               })}
    //               {fileArray.map(x => {
    //                 return (
    //                   <div>
    //                     {x.name}
    //                     {x.url && x.url !== '' && !fail ? <a class="el-icon-download" style="margin:0px 10px; color:#1890ff" target="_blank" download={x.name} href={x.url}></a> : null}
    //                   </div>
    //                 );
    //               })}
    //             </div>
    //           ) : (
    //             <span style="font-size:12px;">暂无数据</span>
    //           )}
    //         </div>
    //       ) : (
    //         <el-upload ref="upload-file" {...uploadProps} style={{ ...style }}>
    //           <el-button size="small" type="primary">
    //             点击上传
    //           </el-button>
    //           <div slot="tip" class="el-upload__tip" style="word-break:break-all;">
    //             文件{fileTypes ? `只能上传 ${fileTypes.join(',')} 格式，` : null}
    //             {`大小范围${this.sizeSmall(min)}-${this.sizeFormatted(max)} `}
    //           </div>
    //         </el-upload>
    //       )}
    //     </el-form-item>
    //   );
    //   //修改 end
    // },
    // 点击文件列表的事件
    async previewFileHandle(file) {
      this.downloadFile(file.url);
    },
    // 获取服务端文件 to blob
    async downLoadByUrl(url) {
      const { data } = await axios({ url, responseType: 'blob' });
      return data;
    },
    // 执行下载动作
    async downloadFile(url) {
      const blob = await this.downLoadByUrl(url);
      const fileName = url.slice(url.lastIndexOf('/') + 1);
      // ie10+
      if (navigator.msSaveBlob) {
        navigator.msSaveBlob(blob, fileName);
      } else {
        const downloadUrl = window.URL.createObjectURL(blob);
        let a = document.createElement('a');
        a.href = downloadUrl;
        a.download = fileName;
        a.click();
        a = null;
      }
    },
    // 文件上传之前的校验
    beforeUploadHandle(file, types, fileList, upload) {
      //const isLt5M = Math.floor(file.size / 1024)
      const isLt5M = file.size; //使用原始大小，计算后会丢失精度，1B会变成0，造成小于1k的文件无法上传
      if (file.size == 0) {
        this.$notify({ title: '错误信息', message: `${isLt5M} K为无效文件，不能上传!`, type: 'error' });
        return false;
      }
      for (let i = 0; i < fileList.length; i++) {
        // 避免上传重复文件
        if (fileList[i].name === file.name) {
          this.$notify({ title: '警告信息', message: `${file.name} 文件已经上传!`, type: 'warning' });
          return false;
        }
      }
      if (types) {
        const isType = types.includes(file.name.slice(file.name.lastIndexOf('.') + 1).toLowerCase());
        if (!isType) {
          this.$notify({ title: '错误信息', message: `附件只能是 ${types.join(',')} 格式!`, type: 'error' });
          return false;
        }
      }
      const max = upload.max || 5120;
      const min = upload.min || 0;
      const xmax = max * 1024; //判断的值放大到B
      const xmin = min * 1024; //判断的值放大到B
      if (isLt5M > xmax) {
        //文件最大
        this.$notify({ title: '错误信息', message: `附件大小不能超过${this.sizeFormatted(max)} !`, type: 'error' });
        return false;
      }
      if (isLt5M < xmin) {
        //文件最小
        this.$notify({ title: '错误信息', message: `附件大小不能小于${this.sizeSmall(min)}!`, type: 'warning' });
        return false;
      }
      this.isupload = false;
    },
    sizeFormatted(maxSize) {
      let result = 0;
      if (maxSize < 1024) {
        result = maxSize + 'K';
      } else {
        result = (maxSize / 1024).toFixed(maxSize % 1024 > 0 ? 2 : 0) + 'M';
      }
      return result;
    },
    sizeSmall(minSize) {
      let result = 0;
      if (minSize < 1024) {
        result = minSize + 'K';
      } else {
        result = (minSize / 1024).toFixed(minSize % 1024 > 0 ? 2 : 0) + 'M';
      }
      return result;
    },
    // 文件被移除
    handleRemove(fieldName, file, fileList) {
      this.form[fieldName] = fileList;
    },
    // 文件上传成功
    successHandle(fieldName, res, file, fileList) {
      if (res.resultCode === 200) {
        this.createFileList(fieldName, file.name, res.data);
        this.$refs[fieldName].clearValidate();
      }
    },
    // 创建上传文件列表
    createFileList(fieldName, name, url = '') {
      this.form[fieldName].push({ name, url });
      this.isupload = true;
    },
    beforeRemove(fieldName, file, fileList) {
      if (!this.isupload) {
        this.$message({
          message: '有正在上传的文件不能进行删除',
          type: 'warning'
        });
        return false;
      }
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    submitForm(ev) {
      //提交验证出错提示
      ev && ev.preventDefault();
      let isErr;
      this.excuteFormData(this.form);
      this.$refs.form.validate(valid => {
        isErr = !valid;
        if (!valid) {
          this.$notify({ title: '错误信息', message: `验证有误，请检查数据格式和必填项!`, type: 'error' });
          return;
        }
        this.$emit('formChange', this.form);
      });
      return isErr;
    },
    async GET_FORM_DATA() {
      //提交验证出错提示
      try {
        const res = await this.getFormData();
        return [false, res];
      } catch (err) {
        this.$notify({ title: '错误信息', message: `验证有误，请检查数据格式和必填项!`, type: 'error' });
        return [true, null];
      }
    }
  }
};
</script>
<style>
.el-upload-list__item-name {
  text-overflow: inherit !important;
  white-space: inherit !important;
}
.imgDIy .el-image__inner {
  max-height: 100% !important;
  max-width: 100% !important;
}
.imgName {
  position: absolute;
  font-size: 12px;
  word-break: break-all;
  line-height: 15px;
  min-height: 20px;
  width: 100%;
  bottom: 0px;
  left: 0px;
  background: rgba(0, 0, 0, 0.5);
  color: #fff;
}
.fileName {
  width: 20px;
  height: 17px;
  padding-top: 3px;
  text-align: center;
  word-break: break-all;
  position: absolute;
  bottom: 0px;
  right: 0px;
  background: rgba(0, 0, 0, 0.5);
  color: #1890ff;
  z-index: 10;
}
</style>
